package com.chenqi.community.controller;

import com.chenqi.community.entity.PageInfo;
import com.chenqi.community.entity.Post;
import com.chenqi.community.entity.Tag;
import com.chenqi.community.entity.Type;
import com.chenqi.community.service.PostService;
import com.chenqi.community.service.TagService;
import com.chenqi.community.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Ardai
 */
@Controller
//@RequestMapping("/community")
public class TypeController {

    @Autowired
    private TypeService typeService;

    @Autowired
    private PostService postService;

    @Autowired
    private TagService tagService;


    /**
     * 根据分类查找帖子
     * @param page
     * @param rows
     * @param tid
     * @param modelAndView
     * @return
     */

    @GetMapping("/type")
    public ModelAndView type(Integer page,Integer rows,Integer tid,ModelAndView modelAndView) {
        //如果不传分页信息进行预处理
        page = page == null ? 1 : page;
        rows = rows == null ? 5 : rows;
        //综合直接返回首页
        if (tid==1){
            modelAndView.setViewName("redirect:/list");
            return modelAndView;
        }
        //其他分类查找(分页查)
        PageInfo pageInfo = new PageInfo();
        Integer total = postService.findPostByTypeIdCount(tid);
        Integer totalPages = total % rows == 0 ? total / rows : total / rows + 1;
        List<Post> postByTypeId = postService.findPostByTypeId(page, rows, tid);
        List<Integer> pageList = new ArrayList<>();
        for(int i=1;i<=totalPages;i++){
            pageList.add(i);
        }
        //封装分页信息
        pageInfo.setPage(page);
        pageInfo.setRows(rows);
        pageInfo.setTotalPages(totalPages);
        pageInfo.setPostList(postByTypeId);
        pageInfo.setPageList(pageList);
        pageInfo.setOther(tid);
        modelAndView.addObject("pageInfo", pageInfo);
        //标签
        List<Tag> tags = tagService.findAllTags();
        modelAndView.addObject("tags", tags);
        //分类
        List<Type> types = typeService.findAllType();
        modelAndView.addObject("types", types);
        //进行什么类型的分页的进行返回
        modelAndView.addObject("status", 1);
        modelAndView.setViewName("index");
        return modelAndView;
    }
}
